<?php

/**
 * Base64上传管理
 */
namespace app\index\controller;


use think\Exception;
use think\Image;

class Upbase64 extends Site
{
    /**
     * base64上传图片
     * @return array
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public function upimg(){
        $info = $this->request->param();
        $upload_result = ['code' => 1, 'msg'=>'请携带base64字符串的前缀',"data"=>[]];
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $info["data"], $result)) {
            //处理base64字符串
            $base64_string= explode(',', $info["data"]); //截取data:image/png;base64, 这个逗号后的字符
            $img_base64= base64_decode($base64_string[1]); //对截取后的字符使用base64_decode进行解码
            //生成hase值
            $key_haxi = hash("sha1", $img_base64);
            $this->set_cache("hash_file",$key_haxi);
            $hash_arr = $this->get_cache("hash_file");
            $is_hash = $this->array_is_str_one($hash_arr,$key_haxi);
            if($is_hash){
                //查询信息并返回
                $fileinfo = $this->get_tab_info(" where hash='".$key_haxi."'");
                if(isset($fileinfo[0]) && $fileinfo[0]){
                    $fileinfo = $fileinfo[0];
                    $data=['uuid'=>$fileinfo['uuid'],'jpg_url'=>get_current_url_ym().$fileinfo['file_path'].$fileinfo['file_name'],'jpg_url_sn'=>$fileinfo['file_name_sn']?get_current_url_ym().$fileinfo['file_path'].$fileinfo['file_name_sn']."":"","size"=>$fileinfo['size'],'hash'=>$key_haxi];
                    $data['src']=$data['jpg_url'];
                    $fileinfo=null;$hash_arr=null;$is_hash=null;$hash=null;
                    return json(['code'=>0,'msg'=>"ok",'data'=>$data]);
                }
                $fileinfo=null;
            }
            //获取文件大小
            $res = self::upimg_base($img_base64,$result);
            $upload_result["code"] = $res['status']?0:2;
            $upload_result['msg'] = $res['msg']."，".$res["err_info"];
            if($res['status']){
                //成功
//                //存入数据库
                $uuid = $this->uuid();
                $this->add_tab_info([
                    'uuid'=>$uuid,
                    'hash'=>$key_haxi,
                    'file_name'=>$res["path"],
                    'file_path'=>"/uploads/img/".date("Ym")."/",
                    'file_name_sn'=>$res["full_path"],
                    'size'=>number_format($res["size"]/1024,2,".",""),
                    'type'=>$info["type"]
                ]);
                $black_url =get_current_url_ym().DS."uploads".DS."img".DS.date("Ym");
                $upload_result["data"]=[
                    'uuid'=>$uuid,
                    'jpg_url'=>$black_url.'/'.$res["path"],
                    'src'=>$black_url.'/'.$res["path"],
                    'jpg_url_sn'=>$res["full_path"]?$black_url.'/'.$res["full_path"]:"",
                    "size"=>number_format($res["size"]/1024,2,".",""),
                    'hash'=>$key_haxi
                ];
                $uuid = null;$black_url=null;
            }
            $res=null;$size=null;$is_hash=null;$hash_arr=null;$key_haxi=null;$img_base64=null;$result=null;
        }
        $info=null;
        return json($upload_result);
    }

    /**
     * 生成图片文件并返回处理信息
     * @param $img_base64 (替换处理后的base64文件)
     * @param $result (正则处理的base64文件)
     * @return array (状态，描述，错误，地址，图片大小)
     */
    private function upimg_base($img_base64,$result){
        //上传目录
        $basedir = ROOT_PATH.DS."public".DS."uploads".DS."img".DS.date("Ym");
        //后缀
        $img_suffix = $result[2];//文件后缀
        //文件名
        // $filename = uniqid();//文件名
        $filename = date('YmdHis',time());//文件名
        //文件完整路径/public/uploads/
        $filepath = $basedir. DS . $filename . "." . $img_suffix;
        //目录若果不存在,则创建目录
        if(!is_dir($basedir)){
            mkdir($basedir,0777,true);
            chmod($basedir,0777);
        }
        //上传文件
//        try {
            file_put_contents($filepath, $img_base64);
            $size = file_get_contents($filepath);
            //判断是否生成缩略图
            $size_img = strlen($size)/1024/1024;
            $full_name="";
            if($size_img > 1){
                vendor("topthink.think-image.src.Image",'.php');
                $imgaes= Image::open($filepath);
                $width = $imgaes->width();
                $height = $imgaes->height();
                $full_name = "_slt_".$filename . "." . $img_suffix;
                if($size_img > 5){
                    $width = $width/10;
                    $height = $height/10;
                }else{
                    $width = $width/2;
                    $height = $height/2;
                }
                $imgaes->thumb($width,$height)->save($basedir.DS.$full_name);
                $imgaes=null;$width=null;$height=null;
            }
            //返回地址前缀
            return ['status' => true, 'msg'=>'上传成功','err_info'=>'','path'=>$filename.".".$img_suffix,"full_path"=>$full_name,'size'=>strlen($size)];
//        } catch (Exception $e) {
//            return ['status' => false, 'msg'=>'上传失败','err_info'=>$e->getMessage()];
//        }
    }
}